package com.itlong.cloud.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.DTO.app.old.AppOldDeviceRecordDto;
import com.itlong.cloud.POJO.VO.app.old.AppOldDeviceRecordVO;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.dao.IAppDevicePassRecordDao;
import com.itlong.cloud.app.dao.IAppOldDeviceRecordDao;
import com.itlong.cloud.app.service.IAppOldDeviceRecordService;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *     旧版APP_用户通行记录接口实现类
 * </desc>
 * @createDate 2017/11/10
 */
@Service
public class AppOldDeviceRecordServiceImpl implements IAppOldDeviceRecordService{
    private static final Logger LOG = LoggerFactory.getLogger(AppOldDeviceRecordServiceImpl.class);


    @Autowired
    IAppOldDeviceRecordDao iAppOldDeviceRecordDao;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    @Autowired
    IAppDevicePassRecordDao iAppDevicePassRecordDao;

    @Autowired
    private MessageSender messageSender;
    /**
     * <desc>
     *     旧版APP_查询通行记录
     * </desc>
     * @param userId 用户的用户ID
     * @param pageNo
     * @param pageSize
     * @param projectId 当前项目编号
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/8
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message getDeviceRecord(String userId,Integer pageNo,Integer pageSize,String projectId) throws Exception{
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        if (StringUtils.isNotBlank(projectId)){
            params.put("projectId",projectId);
        }
        Page page = new Page();
        if (pageNo==0){
            pageNo=0;
        }
        if (pageSize==0){
            pageSize = 10;
        }
        page.getPage().setCurrentPage(pageNo+"");
        page.getPage().setPageSize(pageSize+"");
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());
        List<AppOldDeviceRecordDto> userDeviceRecordList = iAppOldDeviceRecordDao.getUserRecord(params);
        List<AppOldDeviceRecordVO> dtos = new ArrayList<>();
        if (userDeviceRecordList != null&&userDeviceRecordList.size()>0){
            for (AppOldDeviceRecordDto appOldDeviceRecordDto:userDeviceRecordList){
                AppOldDeviceRecordVO dto = new AppOldDeviceRecordVO();
                BeanUtils.copyProperties(appOldDeviceRecordDto, dto);
                dto.setPassTime(appOldDeviceRecordDto.getPassTime().getTime());
                dtos.add(dto);
            }
        }
        return  new Message(Code.SUCCESS,"",dtos);
    }
    /**
     * <desc>
     *     旧版APP_上传通行记录
     * </desc>
     * @param userId
     * @param recordJson
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/9
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message deviceRecordUpload(String userId,String recordJson) throws Exception{
        List<AppOldDeviceRecordDto> drl = null;
        Date now = new Date();
        List<AppOldDeviceRecordDto> adddrList = null;
        try {
            drl = JSONObject.parseObject(recordJson, new TypeReference<List<AppOldDeviceRecordDto>>() {
            });
        }catch (Exception e){
            LOG.error("【旧版APP_通行记录上传转换失败】"+"\n"+recordJson);
        }
        if (drl == null||drl.size() == 0){
            return new Message(Code.PARAM_ERR);
        }else {
            adddrList = new ArrayList<>();
            for (AppOldDeviceRecordDto deviceRecord:drl){
                if (!(StringUtils.isEmpty(deviceRecord.getDeviceUnique())||deviceRecord.getPassTime() == null||deviceRecord.getOpenType() == null)) {
                    String roomNums = deviceRecord.getRoomNum();
                    StringBuffer roomNum = new StringBuffer();
                    if(StringUtils.isNotEmpty(roomNums)) {
                        String[] roomNumArr = roomNums.split(",");
                        for(int i=0;i<roomNumArr.length;i++) {
                            if(roomNumArr[i].length() == 4) {
                                roomNum.append(roomNumArr[i]);
                            } else if(roomNumArr[i].length() == 17){
                                roomNum.append(roomNumArr[i].substring(13, 17));
                            }
                            if(i != roomNumArr.length-1) {
                                roomNum.append(",");
                            }
                        }
                        deviceRecord.setRoomNum(roomNum.toString());
                    }
                    deviceRecord.setUserId(userId);
                    deviceRecord.setProjectId(deviceRecord.getDeviceUnique().substring(0,8));
                    deviceRecord.setSynchro(0);
                    deviceRecord.setCreateTime(new Date());
                    deviceRecord.setStatus(DataStatusEnum.NORMAL.getType());
                    deviceRecord.setIsOpen("0");
                    deviceRecord.setDeviceName(deviceRecord.getDeviceName());
                    //检查是否是门禁类型
                    if(deviceRecord.getDeviceUnique().substring(8,9).equals(PropertyEquipTypeEnum.ENTRANCE.getType().toString())){
                        deviceRecord.setDeviceType(PropertyEquipTypeEnum.ENTRANCE.getType().toString());
                    }else if(deviceRecord.getDeviceUnique().substring(8,9).equals(PropertyEquipTypeEnum.ELEVATOR.getType().toString())){//检查是否是电梯类型
                        deviceRecord.setDeviceType(PropertyEquipTypeEnum.ELEVATOR.getType().toString());
                    }else if(deviceRecord.getDeviceUnique().substring(8,9).equals(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType().toString())){//检查是否是云对讲类型
                        deviceRecord.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType().toString());
                    }
                    //查询设备名称
                    if(StringUtils.isBlank(deviceRecord.getDeviceName()) && StringUtils.isNotBlank(deviceRecord.getDeviceUnique()) && StringUtils.isNotBlank(deviceRecord.getDeviceType())){
                        deviceRecord.setDeviceName(iAppDevicePassRecordDao.getDeviceNameByDeviceUnique(deviceRecord.getDeviceUnique(),Integer.valueOf(deviceRecord.getDeviceType())));
                    }
                    deviceRecord.setUploadTime(now);
                    deviceRecord.setAutoIndex(LogicIdUtil.bussinessId());
                    if (StringUtils.isBlank(deviceRecord.getOpenCount())){
                        deviceRecord.setOpenCount("1");
                    }
                    adddrList.add(deviceRecord);
                }
            }
        }
        if (adddrList != null&&adddrList.size()>0){
            iAppOldDeviceRecordDao.saveBatch(adddrList);
        }
        return  new Message(Code.SUCCESS);
    }
}
